package mspbots.autotask.data.core.contracts;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import mspbots.autotask.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.time.LocalDateTime;

@Log4j2
@Component
@RequiredArgsConstructor
public class ContractServiceBundleUnitsReceiver extends AbstractToolsUtil {

    private final ContractServiceBundleUnitsRepository contractServiceBundleUnitsRepository;

    @RabbitListener(queues = "auto-task.contract-service-bundle-units.sync")
    public void syncTask(ResultMsg content) {

        ContractServiceBundleUnit contractServiceBundleUnit = ContractServiceBundleUnit.builder()
                .otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
                .updatedTime(super.getDateTimeValue(content.getEntity().get("startDate")))
                .createdTime(LocalDateTime.now())
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(contractServiceBundleUnit.getOtherId())) {
            return;
        }

        this.contractServiceBundleUnitsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(oldServiceCallTicketResources -> {
                    contractServiceBundleUnit.setId(oldServiceCallTicketResources.getId());
                    return contractServiceBundleUnit;
                })
                .defaultIfEmpty(contractServiceBundleUnit)
                .flatMap(this.contractServiceBundleUnitsRepository::save)
                .block(Duration.ofSeconds(10));


    }


}
